package drivers

import (
	"fmt"
	"strings"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

// NewGBase8sDialector 创建南大通用GBase 8s数据库驱动
// GBase 8s 基于PostgreSQL协议实现，支持SQL标准和PostgreSQL兼容语法
func NewGBase8sDialector(host, userName, password, database string, port int) gorm.Dialector {
	dsn := BuildGBase8sDsn(host, userName, password, database, port)
	fmt.Println("GBase 8s数据库连接信息dsn：", dsn)

	// 使用PostgreSQL驱动连接GBase 8s数据库
	// GBase 8s完全兼容PostgreSQL协议
	return postgres.Open(dsn)
}

// BuildGBase8sDsn 构建GBase 8s数据库连接字符串
// GBase 8s使用PostgreSQL兼容的DSN格式
func BuildGBase8sDsn(host, userName, password, database string, port int) string {
	// 如果database包含"."，则分割为数据库名.schema名
	// 否则默认数据库为linkdood，database作为schema
	var dbname, schema string
	if strings.Contains(database, ".") {
		parts := strings.Split(database, ".")
		dbname = parts[0]
		schema = parts[1]
	} else {
		dbname = database // 数据库名
		schema = "public" // database参数作为schema
	}

	return fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable TimeZone=Asia/Shanghai connect_timeout=10 search_path=%s",
		host, port, userName, password, dbname, schema)
}
